//
//  HMTabBar.swift
//  MicroBlog
//
//  Created by Apple on 16/9/19.
//  Copyright © 2016年 Apple. All rights reserved.
//

import UIKit

//代理
protocol HMTabBarDelegate: NSObjectProtocol{
    func didSelectedComposeButton()
}

class HMTabBar: UITabBar {
    //点击按钮的闭包
    var composeButtonClosoure: (()->())?
    weak var tabBarDelegate: HMTabBarDelegate?
    // 懒加载
    private lazy var composeButton: UIButton = {
        let button = UIButton()
        //添加点击事件
        button.addTarget(self, action: #selector(buttonClick), for: .touchUpInside)
        //设置图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), for: .normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        //设置背景图
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), for: .normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), for: .highlighted)
        
        button.sizeToFit()
        return button
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not complement")
    }
    //添加子控件
    private func setupUI() {
        //去除黑边效果
        backgroundImage = UIImage(named: "tabbar_background")
        addSubview(composeButton)
    }
    
    //点击事件
    func buttonClick() {
        //执行闭包
        composeButtonClosoure?()
        //调用代理
        tabBarDelegate?.didSelectedComposeButton()
    }
    //设置子控件的位置
    override func layoutSubviews() {
        super.layoutSubviews()
        //设置自定义按钮的中心
        composeButton.centerX = width / 2
        composeButton.centerY = height / 2
        //计算每个按钮的宽度
        let itemWidth = width / 5
        //遍历子控件,记录下标
        var index = 0
        for value in subviews{
            if value.isKind(of: NSClassFromString("UITabBarButton")!) {
                value.width = itemWidth
                value.x = CGFloat(index) * itemWidth
                index += 1
                //设置第三个按钮的宽度多偏移一个按钮宽度
                if index == 2 {
                    index += 1
                }
            }
        }
    }
}
